<template>
  <div class="card-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <span class="search-label">车牌号码：</span>

      <el-input
        v-model="params.carNumber"
        clearable
        placeholder="请输入内容"
        class="search-main"
      />
      <span class="search-label">车主姓名：</span>

      <el-input
        clearable
        v-model="params.personName"
        placeholder="请输入内容"
        class="search-main"
      />
      <span class="search-label">状态：</span>

      <el-select v-model="params.cardStatus">
        <el-option
          v-for="item in cardStatusList"
          :key="item.id"
          :value="item.id"
          :label="item.name"
        />
      </el-select>

      <el-button type="primary" class="search-btn" @click="doSearch"
        >查询</el-button
      >
    </div>

    <!-- 新增删除操作区域 -->
    <div class="create-container">
      <el-button type="primary" @click="showAddDialog = true"
        >添加月卡</el-button
      >
      <el-button @click="delCartList">批量删除</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="cardList"
        @selection-change="handleSelectionChange"
      >
        <!-- 选择行 -->
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" />
        <el-table-column label="车主名称" prop="personName" />
        <el-table-column label="联系方式" prop="phoneNumber" />
        <el-table-column label="车牌号码" prop="carNumber" />
        <el-table-column label="车辆品牌" prop="carBrand" />
        <el-table-column label="剩余有效天数" prop="totalEffectiveDate" />
        <el-table-column
          label="状态"
          prop="cardStatus"
          :formatter="formatStatus"
        />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="{ row }">
            <el-button size="mini" type="text">续费</el-button>

            <el-button size="mini" type="text">查看</el-button>

            <el-button size="mini" type="text" @click="editCard(row.id)"
              >编辑</el-button
            >

            <el-button size="mini" type="text" @click="delCard(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :page-size="params.pageSize"
        :total="total"
        @current-change="pageChange"
      />
    </div>

    <!-- 添加月卡 -->
    <el-dialog title="添加月卡" width="580px" :visible.sync="showAddDialog">
      <div class="form-container">
        <el-form ref="addForm" :model="addForm" :rules="addFormRules">
          <div class="title">车辆信息</div>
          <el-form-item label="车主姓名" prop="personName" :show-message="true">
            <el-input v-model="addForm.personName" />
          </el-form-item>
          <el-form-item label="车辆品牌" prop="carBrand" :show-message="true">
            <el-input v-model="addForm.carBrand" />
          </el-form-item>

          <el-form-item
            label="联系方式"
            prop="phoneNumber"
            :show-message="true"
          >
            <el-input v-model="addForm.phoneNumber" />
          </el-form-item>

          <el-form-item label="车辆号码" prop="carNumber" :show-message="true">
            <el-input v-model="addForm.carNumber" />
          </el-form-item>

          <div class="title">最新一次月卡缴费信息</div>
          <el-form-item
            label="开始日期"
            prop="cardStartDate"
            :show-message="true"
          >
            <el-date-picker
              v-model="addForm.cardStartDate"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>

          <el-form-item
            label="结束日期"
            prop="cardEndDate"
            :show-message="true"
          >
            <el-date-picker
              v-model="addForm.cardEndDate"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>

          <el-form-item
            label="支付金额"
            prop="paymentAmount"
            :show-message="true"
          >
            <el-input v-model="addForm.paymentAmount" />
          </el-form-item>

          <el-form-item
            label="支付方式"
            prop="paymentMethod"
            :show-message="true"
          >
            <el-select v-model="addForm.paymentMethod">
              <el-option
                v-for="item in paymentMethods"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button size="mini" @click="resetForm">重置</el-button>
        <el-button size="mini" type="primary" @click="submitForm"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>


<script>
import { createCardAPI } from "@/api/add";
import {
  getCardListAPI,
  getCardDetailAPI,
  delCardAPI,
  delCardListAPI,
} from "@/api/card";
import dayjs from "dayjs";
export default {
  data() {
    const validaeCarNumber = (rule, value, callback) => {
      const plateNumberRegex = /^[\u4E00-\u9FA5][\da-zA-Z]{6}$/;
      if (plateNumberRegex.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的车牌号"));
      }
    };
    return {
      //已选列表
      selectedCarList: [],
      params: {
        page: 1,
        pageSize: 10,
        carNumber: null,
        personName: null,
        cardStatus: null,
        startTime: null,
        endTime: null,
      },
      total: 0,
      cardList: [],
      cardStatusList: [
        {
          id: null,
          name: "全部",
        },
        {
          id: 0,
          name: "可用",
        },
        {
          id: 1,
          name: "已过期",
        },
      ],
      // 添加卡片对话框信息
      addForm: {
        personName: "",
        phoneNumber: "",
        carNumber: "",
        cardStartDate: "",
        cardEndDate: "",
        paymentAmount: "",
        paymentMethod: "",
        carBrand: "",
      },
      //支付方式
      paymentMethods: [
        { value: "WeChat", label: "微信支付" },
        { value: "Alipay", label: "支付宝" },
        { value: "Cash", label: "银行卡" },
      ],
      //信息
      addFormRules: {
        personName: [
          { required: true, message: "请输入车主姓名", trigger: "blur" },
        ],
        phoneNumber: [
          { required: true, message: "请输入联系方式", trigger: "blur" },
        ],
        carNumber: [
          { required: true, message: "请输入车牌号码", trigger: "blur" },
          {
            validator: validaeCarNumber,
            trigger: "blur",
          },
        ],
        carBrand: [
          { required: true, message: "请输入车主姓名", trigger: "blur" },
        ],
        cardStartDate: [
          { required: true, message: "请选择开始日期", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请选择开始日期"));
                return;
              }
              const selectedDate = dayjs(value);
              const today = dayjs();
              if (selectedDate.isBefore(today, "day")) {
                callback(new Error("开始日期不能早于今天"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        //日期选择器验证
        cardEndDate: [
          { required: true, message: "请选择结束日期", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请选择结束日期"));
                return;
              }
              const startDate = dayjs(this.addForm.cardStartDate);
              const endDate = dayjs(value);
              if (endDate.isBefore(startDate, "day")) {
                callback(new Error("结束日期不能早于开始日期"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      //添加月卡显示隐藏
      showAddDialog: false,
    };
  },
  mounted() {
    this.getCardList();
  },
  methods: {
    //批量选择获取信息
    handleSelectionChange(rowList) {
      // console.log(rowList);
      this.selectedCarList = rowList;
    },
    //批量删除月卡
    delCartList() {
      this.$confirm("此操作将永久删除选择的月卡, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 处理id
          await delCardListAPI(this.selectedCarList.map((item) => item.id));
          this.getCardList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((error) => {
          // console.log(error);
        });
    },
    //删除月卡
    delCard(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await delCardAPI(id);
          this.getCardList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((error) => {
          // console.log(error);
        });
    },

    // 编辑月卡
    async editCard(id) {
      try {
        const res = await getCardDetailAPI(id);
        if (res.code === 10000) {
          this.addForm = {
            ...res.data,
            // cardStartDate: res.data.startDate,
            // cardEndDate: res.data.endDate
          };
          this.showAddDialog = true;
        } else {
          this.$message.error(res.msg || "获取月卡信息失败");
        }
      } catch (error) {
        this.$message.error("获取月卡信息失败");
      }
    },

    // 调用接口之前把页数参数重置为1
    doSearch() {
      this.params.page = 1;
      this.getCardList();
    },
    //获取信息
    async getCardList() {
      const res = await getCardListAPI(this.params);
      this.cardList = res.data.rows;
      this.total = res.data.total;
    },
    formatStatus(row) {
      const MAP = {
        0: "可用",
        1: "已过期",
      };
      return MAP[row.cardStatus];
    },
    pageChange(page) {
      // 把点击的页数赋值给请求参数页数
      this.params.page = page;
      // 使用最新的请求参数获取列表数据
      this.getCardList();
    },
    resetForm() {
      this.$refs.addForm.resetFields();
    },
    async submitForm() {
      try {
        await this.$refs.addForm.validate();
        // const token = this.$store.state.user.token;
        // 输出完整表单信息用于调试，使用JSON.stringify去除Vue响应式属性
        // console.log(this.addForm);
        // 调用添加月卡接口，发送完整表单数据
        const res = await createCardAPI({
          ...this.addForm,
          // token
        });
        if (res.code === 10000) {
          this.$message.success("添加成功");
          this.getCardList();
          this.$refs.addForm.resetFields();
          this.showAddDialog = false;
        } else {
          this.$message.error(res.msg || "添加失败，请检查表单");
        }
      } catch (error) {
        this.$message.error(msg);
      }
    },
  },
};
</script>


<style lang="scss" scoped>
.card-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;
  .search-main {
    width: 220px;
    margin-right: 10px;
  }
  .search-btn {
    margin-left: 20px;
  }
}
.create-container {
  margin: 10px 0px;
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
.form-container {
  padding: 0px 80px;
}
</style>
